import 'dart:async';
import 'dart:io';
import 'dart:typed_data';

import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:frametrim/map/MapImageUtil.dart';
import 'package:frametrim/utility/log_utils.dart';
import '../../map/const_config.dart';
import 'package:amap_flutter_location/amap_flutter_location.dart';

/*政府端
* 实时监控*/
class GovernmentMonitorPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => GovernmentMonitorState();
}

class GovernmentMonitorState extends State<GovernmentMonitorPage> {
  AMapController? _mapController;

  //需要先设置一个空的map赋值给AMapWidget的markers，否则后续无法添加marker
  final Map<String, Marker> _markers = <String, Marker>{};
  late List<LatLng> makLocations = [
    LatLng(34.80, 113.66), //金水
    LatLng(34.72, 113.64), //二七
    LatLng(34.75, 113.68), //管城
    LatLng(34.75, 113.61), //中原
    LatLng(34.87, 113.62) //惠济
  ];
  late List<String> makerText = ['金水区150', '二七区25', '管城区100', '中原区32', '惠济56'];


  Map<String, Object>? _locationResult;

  StreamSubscription<Map<String, Object>>? _locationListener;

  AMapFlutterLocation _locationPlugin = new AMapFlutterLocation();


  ///自定义定位小蓝点
  MyLocationStyleOptions _myLocationStyleOptions =
  MyLocationStyleOptions(true);

  @override
  void initState() {
    super.initState();
    initLocation();
  }

  @override
  Widget build(BuildContext context) {
    ///使用默认属性创建一个地图
    final AMapWidget map = AMapWidget(
      privacyStatement: ConstConfig.amapPrivacyStatement,
      apiKey: ConstConfig.amapApiKeys,
      //地图样式  默认普通地图 普通视图 normal,卫星视图 satellite, 夜间视图 night, 导航视图 navi, 公交视图 bus,
      mapType: MapType.normal,
      //是否显示3D地图
      buildingsEnabled: true,
      //设置地图默认中心点
      // initialCameraPosition:
      //     CameraPosition(target: LatLng(34.76, 113.78), zoom: 10),
      //是否显示指南针
      compassEnabled: true,
      //比例尺是否显示
      scaleEnabled: true,
      //是否显示路况信息
      trafficEnabled: false,
      //是否显示底图文字
      labelsEnabled: true,
      //旋转手势
      rotateGesturesEnabled: true,
      //滑动手势
      scrollGesturesEnabled: true,
      //倾斜手势
      tiltGesturesEnabled: true,
      //缩放手势
      zoomGesturesEnabled: true,
      //地图创建完成回调,成功后会返回AMapController对象
      onMapCreated: onMapCreated,
      //地图移动回调
      onCameraMove: _onCameraMove,
      // //创建地图时，给marker属性赋值一个空的set，否则后续无法添加marker
      markers: Set<Marker>.of(_markers.values),
      myLocationStyleOptions: _myLocationStyleOptions/*MyLocationStyleOptions(
        true,
        icon:BitmapDescriptor.fromIconPath('image/icon_del.png')
      ),*/
    );

    return Scaffold(
      body: AnnotatedRegion(
        value: SystemUiOverlayStyle.dark,
        child: Container(
          height: MediaQuery
              .of(context)
              .size
              .height,
          width: MediaQuery
              .of(context)
              .size
              .width,
          // child: Text('11'),
          child: map,
        ),
      ),
    );
  }

  void onMapCreated(AMapController controller) {
    setState(() {
      _mapController = controller;
      getApprovalNumber();
      _changeCameraPosition();
      _changeZoom();
      for (int i = 0; i < makLocations.length; i++) {
        _addAreaMarker(makLocations[i], i);
      }
    });
  }

  //地图移动回调
  void _onCameraMove(CameraPosition cameraPosition) {
    if (null == cameraPosition) {
      return;
    }
    print('onCameraMove===> ${cameraPosition.toMap()}');
  }

  // 获取审图号
  void getApprovalNumber() async {
    //普通地图审图号
    String? mapContentApprovalNumber =
    await _mapController?.getMapContentApprovalNumber();
    //卫星地图审图号
    String? satelliteImageApprovalNumber =
    await _mapController?.getSatelliteImageApprovalNumber();
  }

  //改变地图中心点
  void _changeCameraPosition() {
    _mapController?.moveCamera(
      CameraUpdate.newCameraPosition(
        CameraPosition(
          //中心点
            target: LatLng(34.80, 113.66),
            //缩放级别
            zoom: 13,
            //俯仰角0°~45°（垂直与地图时为0）
            tilt: 30,
            //偏航角 0~360° (正北方为0)
            bearing: 0),
      ),
      animated: true,
    );
  }

  //缩放地图级别
  void _changeZoom() {
    CameraUpdate.zoomTo(18);
  }

  ///添加一个区域marker
  Future<void> _addAreaMarker(LatLng mLatLng, int index) async {
    final _markerPosition = mLatLng;
    Widget widget = await buildAreaMarkWidget(index);
    Uint8List? bd = await MapImageUtil.convertWidgetToImage(widget);
    final Marker marker = Marker(
        position: _markerPosition,
        //使用默认hue的方式设置Marker的图标
        icon: BitmapDescriptor.fromBytes(bd!),
        // icon:  BitmapDescriptor.fromIconPath('image/distract_bg.png')
        onTap: (id) {
          LogUtil.d('点击Marker$id');
          setState(() {
            _markers.clear();
            for (int i = 0; i < makLocations.length; i++) {
              _addPointMarker(makLocations[i], i);
            }
          });
        });
    //调用setState触发AMapWidget的更新，从而完成marker的添加
    setState(() {
      //将新的marker添加到map里
      _markers[marker.id] = marker;
    });
  }

  ///添加一个点marker-点
  Future<void> _addPointMarker(LatLng mLatLng, int index) async {
    final _markerPosition = mLatLng;
    Widget widget = await buildPointMarkWidget(index);
    Uint8List? bd = await MapImageUtil.convertWidgetToImage(widget);
    final Marker marker = Marker(
        position: _markerPosition,
        //使用默认hue的方式设置Marker的图标
        icon: BitmapDescriptor.fromBytes(bd!),
        // icon:  BitmapDescriptor.fromIconPath('image/distract_bg.png')
        onTap: (id) {
          LogUtil.d('点击Marker$id');
        });
    //调用setState触发AMapWidget的更新，从而完成marker的添加
    setState(() {
      //将新的marker添加到map里
      _markers[marker.id] = marker;
    });
  }

  //Mark样式-区域
  Future<Widget> buildAreaMarkWidget(int index) async {
    //带图片的时候需要先把图片缓存一下，否则不显示
    AssetImage provider = AssetImage('image/distract_bg.png');
    await precacheImage(provider, context);
    // Image image = Image(image: provider);
    return Container(
      alignment: Alignment.center,
      width: 150,
      height: 150,
      decoration: BoxDecoration(
        image: DecorationImage(image: AssetImage('image/distract_bg.png')),
      ),
      child: Directionality(
          textDirection: TextDirection.ltr,
          child: Text(makerText[index],
              style: TextStyle(
                  color: Colors.white,
                  fontSize: 25,
                  fontWeight: FontWeight.bold))),
    );
  }

  //Mark样式-区域
  Future<Widget> buildPointMarkWidget(int index) async {
    //带图片的时候需要先把图片缓存一下，否则不显示
    AssetImage provider = AssetImage('image/cb_select.png');
    await precacheImage(provider, context);
    // Image image = Image(image: provider);
    return Container(
      alignment: Alignment.center,
      width: 150,
      height: 150,
      decoration: BoxDecoration(
        image: DecorationImage(image: AssetImage('image/cb_select.png')),
      ),
      child: Directionality(
          textDirection: TextDirection.ltr,
          child: Text("11",
              style: TextStyle(
                  color: Colors.white,
                  fontSize: 25,
                  fontWeight: FontWeight.bold))),
    );
  }

  /*地图定位*/
  void initLocation() {
    //高德定位
    AMapFlutterLocation.updatePrivacyShow(true, true);
    AMapFlutterLocation.updatePrivacyAgree(true);
    AMapFlutterLocation.setApiKey(
        "8c278373b54c9c393c74f1d1a2d31d49", "ios ApiKey");
    ///iOS 获取native精度类型
    if (Platform.isIOS) {
      requestAccuracyAuthorization();
    }
    ///注册定位结果监听
    _locationListener = _locationPlugin
        .onLocationChanged()
        .listen((Map<String, Object> result) {
      setState(() {
        _locationResult = result;
        LogUtils.e("高德定位==========="+result.toString());
        LogUtils.e("高德定位latitude==========="+result['latitude'].toString());
        LogUtils.e("高德定位longitude: ==========="+result['longitude'].toString());
        LogUtils.e("高德定位country: ==========="+result['country'].toString());
        LogUtils.e("高德定位province: ==========="+result['province'].toString());
        LogUtils.e("高德定位city: ==========="+result['city'].toString());
        LogUtils.e("高德定位city: ==========="+result['city'].toString());
        LogUtils.e("高德定位district: ==========="+result['district'].toString());
        LogUtils.e("高德定位adCode: ==========="+result['adCode'].toString());
      });
    });
    _setLocationOption();
  }

  ///设置定位参数
  void _setLocationOption() {
    if (null != _locationPlugin) {
      AMapLocationOption locationOption = new AMapLocationOption();

      ///是否单次定位
      locationOption.onceLocation = false;

      ///是否需要返回逆地理信息
      locationOption.needAddress = true;

      ///逆地理信息的语言类型
      locationOption.geoLanguage = GeoLanguage.DEFAULT;
      locationOption.desiredLocationAccuracyAuthorizationMode =
          AMapLocationAccuracyAuthorizationMode.ReduceAccuracy;
      locationOption.fullAccuracyPurposeKey = "AMapLocationScene";

      ///设置Android端连续定位的定位间隔
      locationOption.locationInterval = 2000;

      ///设置Android端的定位模式<br>
      ///可选值：<br>
      ///<li>[AMapLocationMode.Battery_Saving]</li>
      ///<li>[AMapLocationMode.Device_Sensors]</li>
      ///<li>[AMapLocationMode.Hight_Accuracy]</li>
      locationOption.locationMode = AMapLocationMode.Hight_Accuracy;

      ///设置iOS端的定位最小更新距离<br>
      locationOption.distanceFilter = -1;

      ///设置iOS端期望的定位精度
      /// 可选值：<br>
      /// <li>[DesiredAccuracy.Best] 最高精度</li>
      /// <li>[DesiredAccuracy.BestForNavigation] 适用于导航场景的高精度 </li>
      /// <li>[DesiredAccuracy.NearestTenMeters] 10米 </li>
      /// <li>[DesiredAccuracy.Kilometer] 1000米</li>
      /// <li>[DesiredAccuracy.ThreeKilometers] 3000米</li>
      locationOption.desiredAccuracy = DesiredAccuracy.Best;

      ///设置iOS端是否允许系统暂停定位
      locationOption.pausesLocationUpdatesAutomatically = false;

      ///将定位参数设置给定位插件
      _locationPlugin.setLocationOption(locationOption);

      ///开始定位
      _startLocation();
    }
  }

  ///获取iOS native的accuracyAuthorization类型
  void requestAccuracyAuthorization() async {
    AMapAccuracyAuthorization currentAccuracyAuthorization =
    await _locationPlugin.getSystemAccuracyAuthorization();
    if (currentAccuracyAuthorization ==
        AMapAccuracyAuthorization.AMapAccuracyAuthorizationFullAccuracy) {
      print("精确定位类型");
    } else if (currentAccuracyAuthorization ==
        AMapAccuracyAuthorization.AMapAccuracyAuthorizationReducedAccuracy) {
      print("模糊定位类型");
    } else {
      print("未知定位类型");
    }
  }


  ///开始定位
  void _startLocation() {
    if (null != _locationPlugin) {
      _locationPlugin.startLocation();
    }
  }

  ///停止定位
  void _stopLocation() {
    if (null != _locationPlugin) {
      _locationPlugin.stopLocation();
    }
  }
  @override
  void dispose() {
    super.dispose();

    ///移除定位监听
    if (null != _locationListener) {
      _locationListener!.cancel();
    }

    ///销毁定位
    if (null != _locationPlugin) {
      _locationPlugin.destroy();
    }
  }


}
